package org.shiro.demo.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.shiro.demo.dao.util.QueryCondition;
import org.shiro.demo.entity.Auxiliary;
import org.shiro.demo.entity.Integral;
import org.shiro.demo.entity.Order;
import org.shiro.demo.entity.OrderProp;
import org.shiro.demo.entity.ResponseResult;
import org.shiro.demo.entity.User;
import org.shiro.demo.service.IBaseService;
import org.shiro.demo.service.IUserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/auxiliary")
public class AuxiliaryController {
	@Resource(name = "baseService")
	private IBaseService baseService;
	@Resource
	private IUserService userService;

	/**
	 * 得到积分 金库 待提货等信息
	 * 
	 * @return
	 */
	@RequestMapping(value = "/get")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles("customer")
	public Object get() {
		ResponseResult rr = new ResponseResult();
		try {
			List<QueryCondition> list = new ArrayList<QueryCondition>();
			User user = getCurrentUser();
			list.add(new QueryCondition("user_id", QueryCondition.EQ, user.getId()));
			Integral intergral = (Integral) baseService.getSingleResult(Integral.class, list);
			if (intergral == null) {
				intergral = new Integral();
				intergral.setUser_id(user.getId());
				intergral.setUser_integral_surplus(0);
				intergral.setUser_integral_time(new Date());
				baseService.save(intergral);
			}

			Auxiliary auxiliry = new Auxiliary();
			auxiliry.setIntegral(intergral.getUser_integral_surplus());
			auxiliry.setBalance(0);

			// 查询 代替 提货订单
			List<QueryCondition> list2 = new ArrayList<QueryCondition>();
			list2.add(new QueryCondition("user", QueryCondition.EQ, user));
			OrderProp prop = new OrderProp();
			prop.setId(2L);
			list2.add(new QueryCondition("orderProp", QueryCondition.EQ, prop));
			long num = baseService.getRecordCount(Order.class, list2);
			auxiliry.setBuffer((int) num);// 不会报错的。不过有隐患
			rr.setCode(1);
			rr.setObject(auxiliry);
			return rr;
		} catch (Exception e) {
			e.printStackTrace();
			rr.setCode(0);
			rr.setInfo("参数有误");
			return rr;
		}

	}

	private User getCurrentUser() {
		User customer = (User) SecurityUtils.getSubject().getPrincipal();
		return customer;
	}
}
